/* eslint-disable no-use-before-define */
/* eslint-disable no-multi-assign */

/**
 * [copy 复制功能]
 * @param  {[String]} str     [需要复制的字符串]
 * @param  {[Function]} success [成功后回调函数]
 * @return {[type]}         [description]
 */
// 也可以使用 clipboard.js    http://www.clipboardjs.cn/
export function copyToClipboard(str, success) {
  try {
    const save = function (e) {
      e.clipboardData.setData('text/plain', str)
      e.preventDefault() // 阻止默认行为
    }
    document.addEventListener('copy', save)
    document.execCommand('copy') // 使文档处于可编辑状态，否则无效
    document.removeEventListener('copy', save) // 复制成功移除监听 否则页面其他复制不生效
    success && success()
  } catch (err) {
    alert('浏览器不支持复制方法')
  }
}

export async function syncLoadJS(url, callback) {
  return new Promise(resolve => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    // IE
    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState === 'loaded' || script.readyState === 'complete') {
          script.onreadystatechange = null
          callback && callback()
          resolve()
        }
      }
    } else {
      // 其他浏览器
      script.onload = () => {
        callback && callback()
        resolve()
      }
    }
    script.src = url
    document.getElementsByTagName('head')[0].appendChild(script)
  })
}
// textarea 光标处插入字符串
export function insertText(el, str) {
  if (document.selection) {
    const sel = document.selection.createRange()
    sel.text = str
  } else if (
    typeof el.selectionStart === 'number'
    && typeof el.selectionEnd === 'number'
  ) {
    const startPos = el.selectionStart
    const endPos = el.selectionEnd
    let cursorPos = startPos
    const tmpStr = el.value
    el.value = tmpStr.substring(0, startPos)
      + str
      + tmpStr.substring(endPos, tmpStr.length)
    cursorPos += str.length
    el.selectionStart = el.selectionEnd = cursorPos
  } else {
    el.value += str
  }
  moveEnd(el)
  return el.value
}
export function moveEnd(el) {
  el.focus()
  const len = el.value.length
  if (document.selection) {
    const sel = el.createTextRange()
    sel.moveStart('character', len)
    sel.collapse()
    sel.select()
  } else if (typeof el.selectionStart === 'number' && typeof el.selectionEnd === 'number') {
    el.selectionStart = el.selectionEnd = len
  }
}


//
/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}


// `distance`：返回两点间的距离
// 该代码段通过计算欧几里得距离来返回两点之间的距离。
export const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0)
// distance(1, 1, 2, 3); // 2.23606797749979


// 此代码段可用于确定当前运行时环境是否为浏览器。这有助于避免在服务器（节点）上运行前端模块时出错。
export const isBrowser = () => ![typeof window, typeof document].includes('undefined')

// `scrollToTop`：平滑滚动至顶部
export const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop)
    window.scrollTo(0, c - c / 8)
  }
}
// scrollToTop();

// . `smoothScroll`：滚动到指定元素区域
// 该代码段可将指定元素平滑滚动到浏览器窗口的可见区域
export const smoothScroll = element => element && element.scrollIntoView({
  behavior: 'smooth'
})
// smoothScroll('#fooBar');
// smoothScroll('.fooBar');

// `detectDeviceType`：检测移动/PC设备
export const detectDeviceType = () => (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  ? 'Mobile'
  : 'Desktop')

// `getScrollPosition`：返回当前的滚动位置
// 默认参数为window ，pageXOffset(pageYOffset)为第一选择，没有则用scrollLeft(scrollTop)
export const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
})
// getScrollPosition(); // {x: 0, y: 200}
